#!/usr/bin/python
# changes coordinates of a large folder.
# imports.
import sys
import os
import time
import subprocess

# parameters.
target_file = sys.argv[1]
query_dir = sys.argv[2]
out_dir = sys.argv[3]

# get list of input files.
query_files = os.listdir(query_dir)

# Build commands.
cmds = []
for f in query_files:
	# names.
	in_path = "%s/%s" % (query_dir, f)
	out_path = "%s/%s" % (out_dir, f)
	
	# command.
	cmd = []
	cmd.append("python")
	cmd.append("/home/jlindsay/code/Overlap/overlap.py")
	cmd.append("-m")
	cmd.append("overlap")
	cmd.append("-t")
	cmd.append(target_file)
	cmd.append("-q")
	cmd.append(in_path)
	cmd.append("-o")
	cmd.append(out_path)
	cmds.append(cmd)


# runs processes in buffer.
def buffer_run(cmds, k):
	# instantiate stuff.
	procs = []
	cnt = 0
	sz = len(cmds)
	
	# loop until all cmds are executed.
	while len(cmds) != 0:
		# check alive process.
		alive = 0
		tmp = []
		for p in procs:
			if p.poll() == None:
				alive += 1
				tmp.append(p)
		procs = tmp
		
		# submit or wait.
		if alive < k:
			p = subprocess.Popen(cmds.pop())
			procs.append(p)
			print "running %i of %i" % (cnt, sz)
			cnt += 1
		else:
			time.sleep(10)


# run cmds.
buffer_run(cmds, 30)
	
